package us.gaaoc.framework.webapp.util;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;

/**
 * Implemenation of the BufferedImage creator which uses
 * PDFRenderer and com.sun.pdfview.* .
 * 
 * @author artripa
 *
 */
public class BufferedImageCreatorPDFRendererImpl implements
		BufferedImageCreator {

		private int pageNumber;

		public BufferedImageCreatorPDFRendererImpl(int pageNumber)
		{
			this.pageNumber = pageNumber;
		}
	
		@Override
		public BufferedImage createBufferedImage(byte[] contents)
			throws IOException {
			 ByteBuffer buf = ByteBuffer.wrap(contents);			 
		     PDFFile pdffile = new PDFFile(buf);
		     return createBufferedImage(pdffile);
		}
		
		protected BufferedImage createBufferedImage(PDFFile pdffile)
		{
			  PDFPage page = pdffile.getPage(pageNumber);
	        Rectangle rect = new Rectangle(0,0,
	                (int)page.getBBox().getWidth(),
	                (int)page.getBBox().getHeight());
	        
	        //generate the image
	        Image img = page.getImage(
	                rect.width, rect.height, //width & height
	                rect, // clip rect
	                null, // null for the ImageObserver
	                true, // fill background with white
	                true  // block until drawing is done
	                );
	        
	         int width = img.getWidth(null);  
	         int height = img.getHeight(null);  
	         int type = BufferedImage.TYPE_BYTE_GRAY; // you can experiment with this one to increase/decrease quality and file size.  
	         BufferedImage bi = new BufferedImage(width, height, type);  
	         Graphics2D g2d = bi.createGraphics();  
	         g2d.drawImage(img, 0, 0, null);  
	         g2d.dispose();  
	         return bi;		
		}
		
		public BufferedImage createBufferedImage(String filename) throws IOException {
	        File file = new File(filename);
	        RandomAccessFile raf = new RandomAccessFile(file, "r");
	        FileChannel channel = raf.getChannel();
	        ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
	        PDFFile pdffile = new PDFFile(buf);
	        		
	        return createBufferedImage(pdffile);	      	     		
		}
	
}
